<template>
  <div class="register-container">
    <div class="register-box">
      <div class="register-title">
        <h2>食养健康系统</h2>
        <p>注册新账号</p>
      </div>

      <van-form ref="registerFormRef" @submit="handleRegister">
        <van-cell-group inset>
          <van-field
            v-model="registerForm.username"
            name="username"
            label="用户名"
            placeholder="请输入用户名"
            :rules="[
              { required: true, message: '请输入用户名' },
              { min: 3, max: 20, message: '用户名长度应为3-20个字符' },
            ]"
          >
            <template #left-icon>
              <van-icon name="user-o" />
            </template>
          </van-field>

          <van-field
            v-model="registerForm.password"
            type="password"
            name="password"
            label="密码"
            placeholder="请输入密码"
            :rules="[
              { required: true, message: '请输入密码' },
              { min: 6, max: 20, message: '密码长度应为6-20个字符' },
            ]"
          >
            <template #left-icon>
              <van-icon name="lock" />
            </template>
          </van-field>

          <van-field
            v-model="registerForm.confirmPassword"
            type="password"
            name="confirmPassword"
            label="确认密码"
            placeholder="请再次输入密码"
            :rules="[
              { required: true, message: '请再次输入密码' },
              { validator: validatePass, message: '两次输入的密码不一致' },
            ]"
          >
            <template #left-icon>
              <van-icon name="lock" />
            </template>
          </van-field>

          <van-field
            v-model="registerForm.nickname"
            name="nickname"
            label="昵称"
            placeholder="请输入昵称"
            :rules="[{ required: true, message: '请输入昵称' }]"
          >
            <template #left-icon>
              <van-icon name="contact" />
            </template>
          </van-field>

          <van-field
            v-model="registerForm.email"
            name="email"
            label="邮箱"
            placeholder="请输入邮箱"
          >
            <template #left-icon>
              <van-icon name="envelop-o" />
            </template>
          </van-field>
        </van-cell-group>

        <div style="margin: 16px">
          <van-button
            round
            block
            type="primary"
            native-type="submit"
            :loading="loading"
          >
            注册
          </van-button>
        </div>
      </van-form>

      <div class="login-link">
        已有账号？
        <a @click="$router.push('/login')">立即登录</a>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from "vue";
import { useRouter } from "vue-router";
import { showToast, showSuccessToast } from "vant";
import { register } from "../api/user";

// 路由实例
const router = useRouter();

// 注册表单引用
const registerFormRef = ref();

// 注册表单数据
const registerForm = reactive({
  username: "",
  password: "",
  confirmPassword: "",
  nickname: "",
  email: "",
});

// 密码确认验证
const validatePass = (val) => {
  return val === registerForm.password;
};

// 注册状态
const loading = ref(false);

// 注册处理
const handleRegister = async () => {
  try {
    loading.value = true;

    // 组装注册数据
    const registerData = {
      username: registerForm.username,
      password: registerForm.password,
      nickname: registerForm.nickname,
      email: registerForm.email,
      status: 1,
    };

    const res = await register(registerData);

    if (res.code === 200) {
      showSuccessToast("注册成功，请登录");
      // 短暂延迟后跳转到登录页，让用户看到成功提示
      setTimeout(() => {
        router.push("/login");
      }, 1000);
    } else {
      // 显示后端返回的错误信息
      showToast({
        message: res.message || "注册失败",
        type: "fail",
      });
    }
  } catch (error) {
    console.error("注册失败", error);
    let errorMsg = "注册失败";
    if (error.response && error.response.data && error.response.data.message) {
      errorMsg = error.response.data.message;
    } else if (error.message) {
      errorMsg = error.message;
    }
    showToast({
      message: errorMsg,
      type: "fail",
    });
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped>
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f7f8fa;
  padding: 20px 0;
}

.register-box {
  width: 85%;
  max-width: 450px;
  padding: 30px 20px;
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 8px 12px rgba(0, 0, 0, 0.05);
}

.register-title {
  text-align: center;
  margin-bottom: 30px;
}

.register-title h2 {
  font-size: 24px;
  color: #323233;
  margin-bottom: 8px;
  font-weight: 600;
}

.register-title p {
  font-size: 14px;
  color: #969799;
}

.login-link {
  text-align: center;
  margin-top: 20px;
  font-size: 14px;
  color: #969799;
}

.login-link a {
  color: #1989fa;
  text-decoration: none;
}
</style>
